package net.fredstar.polarbear;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.security.GeneralSecurityException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

/**
 * TODO Comments.
 * 
 * @author Matthew Blackford [matthew@fredstar.net]
 */
public class SecureClient
{
  public static final int POLAR_BEAR_PORT = 52391;
  
  /**
   * Creates a new {@link SecureClient} instance.
   */
  public SecureClient()
  {

  }
  
  public void initialise() throws IOException, GeneralSecurityException
  {
    // Get the context factory
    SSLContextFactory contextFactory = SSLContextFactory.getInstance();
    
    // Create the context
    SSLContext context = contextFactory.createSecureContext(
        "test/keys/client.keystore", "123456", "test/keys/client.truststore",
        "123456" );
    
    // Create a socket
    SSLSocketFactory socketFactory = context.getSocketFactory();
    SSLSocket socket = (SSLSocket) socketFactory.createSocket( "localhost",
        POLAR_BEAR_PORT );
    
    // Start the handshake process
    socket.startHandshake();

    OutputStream rawOut = socket.getOutputStream();
    OutputStreamWriter streamWriter = new OutputStreamWriter( rawOut );
    BufferedWriter buffered = new BufferedWriter( streamWriter );
    PrintWriter out = new PrintWriter( buffered );
    
    for ( int i = 0; i < 1000; i++ )
    {
      try
      {
        Thread.sleep( 1000 );
      }
      catch ( InterruptedException ex )
      {
        ex.printStackTrace();
      }
      out.println( "Hello " + i );
      out.flush();
    }
    
    socket.close();
  }
  
  /**
   * TODO Comments.
   * 
   * @param args the command line arguments.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  public static void main( final String[] args ) throws IOException,
      GeneralSecurityException
  {
    new SecureClient().initialise();
  }
}
